#include <stdio.h>
#include "calc.h"

#define MAXVAL 100

static void stack_error(bool full, const char *func);

static int sp = 0;
static double val[MAXVAL];

void push(double f)
{
  if (sp < MAXVAL)
    val[sp++] = f;
  else
    stack_error(TRUE, __func__);
}

double pop()
{
  if (sp > 0)
    return val[--sp];
  else {
    stack_error(FALSE, __func__);
    return 0.0;
  }
}

void show_top_stack(void)
{
  if (sp <= 0)
    stack_error(FALSE, __func__);
  else
    printf("top sp: %d, stack: %g\n", sp, val[sp-1]);
}

double get_top_stack(void)
{
  if (sp > 0)
    return val[sp-1];
  else
    stack_error(FALSE, __func__);
  return 0.0;
}

int swap_top_stack(void)
{
  if (sp <= 0) {
    stack_error(FALSE, __func__);
    return -1;
  }
  int i = sp - 1;
  double c;
  c = val[i];
  val[i] = val[i-1];
  val[i-1] = c;
  return 0;
}

int clean_stack(void)
{
  /* memset(val, 0, sizeof(double) * sp); */
  int i;
  for (i = 0; i < sp; i++) {
    val[i] = 0;
  }
  return 0;
}

static void stack_error(bool full, const char *s)
{
  fprintf(stderr, "error: stack is %s: %s\n", full ? "full" : "empty", s);
}
